<template>
  <div class="app-container">
    <el-tabs v-model="activeName">
      <el-tab-pane label="中国主导相关指标" name="first">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="指标名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入指标名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建时间" prop="time">
            <el-date-picker
              v-model="queryParams.time"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd2"
              v-hasPermi="['system:indicator:add']"
            >新增一级指标</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="selectedRows.length === 0"
              @click="handleDelete"
              v-hasPermi="['system:indicator:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-refresh"
              size="mini"
              @click="reset"
            >刷新缓存</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-if="activeName == 'first'"  v-loading="loading" :data="dataListTab1" @selection-change="handleSelectionChange"
                  row-key="indicatorName"
                  :default-expand-all="isExpandAll"
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="指标名称" align="left" prop="indicatorName" />
          <el-table-column label="来源数据" align="center" prop="dataSource" :show-overflow-tooltip="true" />
          <el-table-column label="计算方式" align="center"  prop="calculationMethod" :show-overflow-tooltip="true">
            <template #default="scope">
              <div v-katex:auto >{{ scope.row.calculationMethod }}</div>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="handleAdd(scope.row)"
                v-hasPermi="['system:indicator:add']"
              >新增下级指标</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:indicator:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete2(scope.row)"
                v-hasPermi="['system:indicator:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="中国参与相关指标" name="second">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="指标名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入指标名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="来源数据" prop="dataSource">
            <el-input
              v-model="queryParams.dataSource"
              placeholder="来源数据"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建时间" prop="time">
            <el-date-picker
              v-model="queryParams.time"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd3"
              v-hasPermi="['system:indicator:add']"
            >新增一级指标</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="selectedRows.length === 0"
              @click="handleDelete"
              v-hasPermi="['system:indicator:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-refresh"
              size="mini"
              @click="reset"
            >刷新缓存</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table v-if="activeName == 'second'" v-loading="loading" :data="dataListTab2" @selection-change="handleSelectionChange"
                  row-key="indicatorName"
                  :default-expand-all="isExpandAll"
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="指标名称" align="left" prop="indicatorName" />
          <el-table-column label="来源数据" align="center" prop="dataSource" :show-overflow-tooltip="true" />
          <el-table-column label="计算方式" align="center"  prop="calculationMethod" :show-overflow-tooltip="true">
            <template #default="scope">
              <div v-katex:auto >{{ scope.row.calculationMethod }}</div>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="handleAdd(scope.row)"
                v-hasPermi="['system:indicator:add']"
              >新增下级指标</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:indicator:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete2(scope.row)"
                v-hasPermi="['system:indicator:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <pagination
      v-show="currentTotal>0"
      :total="currentTotal"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="handlePagination"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="indicatorVo" :rules="rules" label-width="100px">
        <el-form-item label="指标名称" prop="indicatorName">
          <el-input v-model="indicatorVo.indicatorName" placeholder="请输入指标名称" maxlength="50" show-word-limit/>
          <div class="required-tip">指标名称必须以大写字母开头，只能包含字母、数字、下划线和中文</div>
        </el-form-item>
        <el-form-item label="指标描述" prop="indicatorDescription">
          <el-input v-model="indicatorVo.indicatorDescription" placeholder="请输入指标描述信息" type="textarea" maxlength="200" show-word-limit/>
        </el-form-item>
        <el-form-item label="来源数据" prop="dataSource">
          <el-input v-model="indicatorVo.dataSource" type="textarea" placeholder="请输入来源数据" maxlength="500" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="计算方式" prop="calculationMethod">
          <el-input v-model="indicatorVo.calculationMethod" type="textarea" placeholder="请输入计算方式" maxlength="1000" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="indicatorVo.description" type="textarea" placeholder="请输入备注" maxlength="500" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改指标菜单 -->
    <el-dialog :title="title2" :visible.sync="open2" width="500px" append-to-body>
      <el-form ref="form" :model="indicatorVo" :rules="rules" label-width="100px">
        <el-form-item label="指标名称" prop="indicatorName">
          <el-input v-model="indicatorVo.indicatorName" placeholder="请输入新指标名称" maxlength="50" show-word-limit/>
          <div class="required-tip">指标名称必须以大写字母开头，只能包含字母、数字、下划线和中文</div>
        </el-form-item>
        <el-form-item label="指标描述" prop="indicatorDescription">
          <el-input v-model="indicatorVo.indicatorDescription" placeholder="请输入新指标描述信息" type="textarea" maxlength="200" show-word-limit/>
        </el-form-item>
        <el-form-item label="来源数据" prop="dataSource">
          <el-input v-model="indicatorVo.dataSource" type="textarea" placeholder="请输入新来源数据" maxlength="500" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="计算方式" prop="calculationMethod">
          <el-input v-model="indicatorVo.calculationMethod" type="textarea" placeholder="请输入新计算方式" maxlength="1000" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="indicatorVo.description" type="textarea" placeholder="请输入新备注" maxlength="500" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getIndicatorsTree, search, delIndicator, addIndicator,updateIndicator} from "@/api/indicator/indicator";
  import 'katex/dist/katex.min.css';
  import katex from 'katex/dist/katex.min'
  import 'katex/dist/contrib/auto-render.min'
  import VueKatex from 'vue-katex';

  export default {
  name: "indexManager",
    data() {
  return {
  // 遮罩层
  loading: true,
  dataList: [],  // 原始数据列表
  dataListTab1: [],  // 第一个标签页的数据（中国主导）
  dataListTab2: [],  // 第二个标签页的数据（中国参与）
  activeName: 'first', // 当前激活的标签页
  // 显示搜索条件
  showSearch: true,
  total: 0,  // 总数（根据当前 tab 动态计算）
  totalTab1: 0,  // 中国主导指标总数
  totalTab2: 0,  // 中国参与指标总数
      indicatorVo: {
        id: null,
        indicatorName: '',
        indicatorLevel: 2,
        parentIndicatorId: null,
        calculationMethod: '',
        indicatorDescription: '',
        dataSource: '',
        description: '',
        indicatorType:'',
        num: ''
      },
    emptyIndicatorVo:{
      id: null,
      indicatorName: '',
      indicatorLevel: 2,
      parentIndicatorId: null,
      calculationMethod: '',
      indicatorDescription: '',
      dataSource: '',
      description: '',
      indicatorType:'',
      num: ''
    },
  ids:[],
  // 弹出层标题
  title: "",
    title2: "",
  // 是否显示弹出层
  open: false,
    open2: false,
  // 是否展开，默认全部折叠
  isExpandAll: false,
  // 重新渲染表格状态
  refreshTable: true,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    time: [],
    dataSource: null
  },
  // 表单校验
  rules: {
    indicatorName: [
      { required: true, message: "指标名称不能为空", trigger: "blur" },
      { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
      { pattern: /^[A-Z][a-zA-Z0-9_\u4e00-\u9fa5]*$/, message: "指标名称必须以大写字母开头，只能包含字母、数字、下划线和中文", trigger: "blur" }
    ]
    // ,
    // indicatorDescription: [
    //   { required: true, message: "指标描述不能为空", trigger: "blur" },
    //   { min: 1, max: 200, message: "长度在 1 到 200 个字符", trigger: "blur" }
    // ],
    // dataSource: [
    //   { required: true, message: "来源数据不能为空", trigger: "blur" },
    //   { min: 1, max: 500, message: "长度在 1 到 500 个字符", trigger: "blur" }
    // ],
    // calculationMethod: [
    //   { required: true, message: "计算方式不能为空", trigger: "blur" },
    //   { min: 1, max: 1000, message: "长度在 1 到 1000 个字符", trigger: "blur" }
    // ]
  },
  selectedRows: []
};
},
  computed: {
    // 根据当前激活的标签页动态计算总数
    currentTotal() {
      return this.activeName === 'first' ? this.totalTab1 : this.totalTab2;
    }
  },
  created() {
  this.getList();
},
  watch: {
    // 监听 tab 切换，更新 total
    activeName(newVal) {
      this.total = newVal === 'first' ? this.totalTab1 : this.totalTab2;
    }
  },
  methods: {
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    
    /** 处理数据分类和统计 */
    processDataByType(dataList) {
      this.dataListTab1 = [];
      this.dataListTab2 = [];
      
      // 分别统计两个 tab 的数据
      dataList.forEach(item => {
        // 类型 '0' 和 '2' 归类到中国主导
        if (item.indicatorType === '0' || item.indicatorType === '2') {
          this.dataListTab1.push(item);
        } 
        // 类型 '1' 和 '3' 归类到中国参与
        else if (item.indicatorType === '1' || item.indicatorType === '3') {
          this.dataListTab2.push(item);
        }
      });
      
      // 分别设置两个 tab 的总数
      this.totalTab1 = this.dataListTab1.length;
      this.totalTab2 = this.dataListTab2.length;
      
      // 根据当前激活的 tab 设置 total（保持兼容性）
      this.total = this.activeName === 'first' ? this.totalTab1 : this.totalTab2;
    },
    
  /** 查询菜单列表 */
  getList() {
    this.loading = true;
    getIndicatorsTree(this.queryParams).then(response => {
      this.dataList = response.rows;
      this.processDataByType(this.dataList);
      this.loading = false;
    }).catch(error => {
      this.loading = false;
      console.error('获取指标列表失败:', error);
    });
  },
  // 取消按钮
  cancel() {
  this.open = false;
  this.open2=false;
},
  // 表单重置
  reset() {
  this.getList();
  this.indicatorVo = JSON.parse(JSON.stringify(this.emptyIndicatorVo));
},
  /** 搜索按钮操作 */
  handleQuery(resetPageNum = true) {
    if (resetPageNum) {
      this.queryParams.pageNum = 1;
    }
    
    // 检查是否有搜索条件
    const hasSearchCondition = this.queryParams.name || 
                                (this.queryParams.time && this.queryParams.time.length > 0) || 
                                this.queryParams.dataSource;
    
    // 如果没有任何搜索条件，直接调用 getList 获取树形结构
    if (!hasSearchCondition) {
      this.getList();
      return;
    }
    
    // 根据当前标签页确定指标类型
    let indicatorType = null;
    if (this.activeName === 'first') {
      // 中国主导相关指标：类型 '0' 和 '2'
      indicatorType = '0';
    } else if (this.activeName === 'second') {
      // 中国参与相关指标：类型 '1' 和 '3'
      indicatorType = '1';
    }
    
    // 有搜索条件时，使用 search API 进行搜索
    this.loading = true;
    search(
      this.queryParams.name,
      this.queryParams.time && this.queryParams.time.length > 0 ? this.queryParams.time[0] : null,
      this.queryParams.time && this.queryParams.time.length > 1 ? this.queryParams.time[1] : null,
      this.queryParams.dataSource,
      this.queryParams.pageNum,
      this.queryParams.pageSize,
      indicatorType
    ).then(response => {
      // 搜索时直接使用后端返回的数据，不进行重新分类
      if (this.activeName === 'first') {
        this.dataListTab1 = response.rows;
        this.totalTab1 = response.total;
      } else {
        this.dataListTab2 = response.rows;
        this.totalTab2 = response.total;
      }
      this.loading = false;
    }).catch(error => {
      this.loading = false;
      console.error('搜索失败:', error);
    });
  },
  /** 重置按钮操作 */
  resetQuery() {
    this.queryParams = {
      pageNum: 1,
      pageSize: 10,
      name: null,
      time: [],
      dataSource: null
    };
    // 重置时应该调用 getList 获取完整的树形结构，而不是 handleQuery 的搜索结果
    this.getList();
  },

  /** 分页按钮操作 */
  handlePagination(pagination) {
    this.queryParams.pageNum = pagination.page;
    this.queryParams.pageSize = pagination.limit;
    
    // 检查是否有搜索条件
    const hasSearchCondition = this.queryParams.name || 
                                (this.queryParams.time && this.queryParams.time.length > 0) || 
                                this.queryParams.dataSource;
    
    // 如果有搜索条件，调用 handleQuery 进行搜索分页，但不重置页码
    // 如果没有搜索条件，调用 getList 获取树形结构
    if (hasSearchCondition) {
      this.handleQuery(false);
    } else {
      this.getList();
    }
  },
  /** 新增下级指标按钮操作 */
  handleAdd(row) {
    this.indicatorVo = JSON.parse(JSON.stringify(this.emptyIndicatorVo));
    if (row.id) {
      this.indicatorVo.id = null;
      this.indicatorVo.parentIndicatorId = row.id;
      this.indicatorVo.indicatorLevel = row.indicatorLevel + 1;
      // 根据父级指标的类型设置子级指标的类型
      this.indicatorVo.indicatorType = row.indicatorType;
    }
    this.open = true;
    this.title = "添加指标菜单";
},
    /** 新增一级指标按钮操作 */
    handleAdd2(){
    this.reset();
      this.indicatorVo.id = null;
      this.indicatorVo.parentIndicatorId = null;
      this.indicatorVo.indicatorLevel = 1;
      this.indicatorVo.indicatorType = "0"; // 中国主导
      this.open = true;
      this.title = "添加指标菜单";
    },
    handleAdd3(){
      this.reset();
      this.indicatorVo.id = null;
      this.indicatorVo.parentIndicatorId = null;
      this.indicatorVo.indicatorLevel = 1;
      this.indicatorVo.indicatorType = "1"; // 中国参与
      this.open = true;
      this.title = "添加指标菜单";
    },

  /** 展开/折叠操作 */
  toggleExpandAll() {
  this.refreshTable = false;
  this.isExpandAll = !this.isExpandAll;
  this.$nextTick(() => {
  this.refreshTable = true;
});
},
  /** 修改按钮操作 */
  handleUpdate(row) {
    this.indicatorVo = Object.assign({}, row);
    this.open2 = true;
    this.title2 = "修改指标";
},
  /** 新增提交按钮 */
  submitForm: function() {
    this.$refs["form"].validate(valid => {
      if (valid) {
        if (this.indicatorVo != undefined) {
          addIndicator(this.indicatorVo).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          }).catch(error => {
            let errorMessage = "新增失败";
            if (error.response && error.response.data && error.response.data.msg) {
              errorMessage = error.response.data.msg;
            } else if (error.message) {
              errorMessage = "新增失败: " + error.message;
            }
            this.$modal.msgError(errorMessage);
          });
        }
      } else {
        this.$modal.msgError("表单验证失败，请检查必填项和输入格式");
        return false;
      }
    });
  },
    /** 修改提交按钮 */
    submitForm2: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.indicatorVo != undefined) {
            updateIndicator(this.indicatorVo).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open2 = false;
              this.getList();
            }).catch(error => {
              let errorMessage = "修改失败";
              if (error.response && error.response.data && error.response.data.msg) {
                errorMessage = error.response.data.msg;
              } else if (error.message) {
                errorMessage = "修改失败: " + error.message;
              }
              this.$modal.msgError(errorMessage);
            });
          }
        } else {
          this.$modal.msgError("表单验证失败，请检查必填项和输入格式");
          return false;
        }
      });
    },
  /** 复选框删除按钮操作 */
  handleDelete() {
    const ids = this.selectedRows.map((item) => item.id);
    if (ids.length === 0) {
      this.$message({
        message: "请先选择要删除的指标",
        type: "warning",
      });
      return;
    }

    this.$modal
      .confirm("此操作将永久删除选中的数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        delIndicator(ids).then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getList();
          this.selectedRows = [];
        }).catch(error => {
          let errorMessage = "删除失败";
          if (error.response && error.response.data && error.response.data.msg) {
            errorMessage = error.response.data.msg;
          } else if (error.message) {
            errorMessage = "删除失败: " + error.message;
          }
          this.$modal.msgError(errorMessage);
        });
      });
},
    /** 行中操作按钮操作 */
    handleDelete2(row) {
      this.ids = [row.id];

      this.$modal
        .confirm("此操作将永久删除选中的数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          delIndicator(this.ids).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getList();
            this.ids = [];
          }).catch(error => {
            let errorMessage = "删除失败";
            if (error.response && error.response.data && error.response.data.msg) {
              errorMessage = error.response.data.msg;
            } else if (error.message) {
              errorMessage = "删除失败: " + error.message;
            }
            this.$modal.msgError(errorMessage);
          });
        });
    }
  }
};
</script>

<style scoped>
.required-tip {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
}
</style>
